package com.zyw.orm.support.page;

import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 分页 ， 供ibatis操作数据分页使用
 *
 * @author zhangyw
 * @date 16/9/5 15:03
 */
public class Page<T> {

    private Integer pageNo; // 页码
    private Integer pageSize; // 页大小 -1 不采用分页
    private int total; // 总记录数

    private List<T> list = new ArrayList<>();

    private T paramBean;

    private List<Sort> orders;
    private boolean dataScope;

    public Page() {
        pageNo = 1;
        pageSize = 10;
    }

    public Integer getPageNo() {
        return pageNo;
    }

    public void setPageNo(Integer pageNo) {
        this.pageNo = pageNo == null ? 1 : pageNo;
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize == null ? 10 : pageSize;
    }

    public int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = total;
    }

    public List<T> getList() {
        return list;
    }

    public void setList(List<T> list) {
        this.list = list;
    }

    public T getParamBean() {
        return paramBean;
    }

    public void setParamBean(T paramBean) {
        this.paramBean = paramBean;
    }

    public List<Sort> getOrders() {
        return orders;
    }

    public void setOrders(List<Sort> orders) {
        this.orders = orders;
    }

    public boolean isDataScope() {
        return dataScope;
    }

    public void setDataScope(boolean dataScope) {
        this.dataScope = dataScope;
    }

    /**
     * 判断是否超出分页结果集
     *
     * @return
     */
    public boolean isOutOfPage() {
        int first = 1;
        int last = (int) Math.ceil((total + 0.0) / (this.pageSize < 1 ? 10 : this.pageSize));
        return pageNo < first || pageNo > last;
    }

    /**
     * 添加排序字段
     *
     * @param field    排序字段名
     * @param sortType 排序类型 asc 升序，desc 倒序
     */
    public void addOrderBy(String field, String sortType) {
        if (StringUtils.isEmpty(field)) {
            return;
        }

        if (orders == null) {
            orders = Lists.newLinkedList();
        }

        orders.add(new Sort(field, sortType));
    }

    /**
     * 是否需要数据过滤
     * @return
     */
    public boolean needDataScope() {
        return this.dataScope;
    }
}
